<template>
  <a-row>
    <a-card :bordered="false">

      <!-- 按钮操作区域 -->
      <a-row style="margin-left: 14px">
        <a-button @click="handleAdd(1)" type="primary">添加分类</a-button>
        <a-button @click="handleAdd(2)" type="primary">添加下级</a-button>
        <a-button title="删除多条数据" @click="batchDel" type="default">批量删除</a-button>
      </a-row>
      <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
        <a-alert type="info" :showIcon="true">
          <div slot="message">
            当前选择：<span v-if="this.currSelected.name">{{ getCurrSelectedTitle() }}</span>
            <a v-if="this.currSelected.title" style="margin-left: 10px" @click="onClearSelected">取消选择</a>
          </div>
        </a-alert>
        <a-input-search @search="onSearch" style="width:100%;margin-top: 10px" placeholder="请输入分类名称"/>
        <!-- 树-->
        <a-col :md="10" :sm="24">
          <template>
            <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
              <span style="user-select: none">
                <a-tree
                  checkable
                  multiple
                  draggable
                  @select="onSelect"
                  @check="onCheck"
                  @rightClick="rightHandle"
                  :selectedKeys="selectedKeys"
                  :checkedKeys="checkedKeys"
                  :treeData="departTree"
                  :checkStrictly="checkStrictly"
                  :expandedKeys="iExpandedKeys"
                  :autoExpandParent="autoExpandParent"
                  @drop="onDrop"
                  @dragend="onDragend"
                  @expand="onExpand"/>
              </span>
              <!--新增右键点击事件,和增加添加和删除功能-->
              <a-menu slot="overlay">
                <a-menu-item @click="handleAdd(3)" key="1">添加</a-menu-item>
                <a-menu-item @click="handleDelete" key="2">删除</a-menu-item>
                <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </a-col>
      </div>
    </a-card>

    <div class="drawer-bootom-button">
      <a-dropdown :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
          <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
          <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
          <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
          <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          树操作
          <a-icon type="up"/>
        </a-button>
      </a-dropdown>
    </div>

    <category-modal ref="categoryModal" @ok="loadTree"></category-modal>
  </a-row>
</template>
<script>
// import DepartModal from './modules/DepartModal'
// import DepartAuthModal from './modules/DepartAuthModal'
import {queryDepartTreeList, searchByKeywords, deleteByDepartId} from '@/api/api'
import {httpAction, deleteAction, putAction} from '@/api/manage'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import CategoryModal from '@/management/common_mng/category/modules/CategoryModal'

export default {
  name: 'CategoryList',
  mixins: [JeecgListMixin],
  components: {
    CategoryModal
  },
  data() {
    return {
      iExpandedKeys: [],
      loading: false,
      autoExpandParent: true,
      currFlowId: '',
      currFlowName: '',
      disable: true,
      treeData: [],
      visible: false,
      departTree: [],
      rightClickSelectedKey: '',
      rightClickSelectedOrgCode: '',
      hiding: true,
      model: {},
      dropTrigger: '',
      depart: {},
      // columns: columns,
      disableSubmit: false,
      checkedKeys: [],
      selectedKeys: [],
      autoIncr: 1,
      currSelected: {},
      allTreeKeys: [],
      allTreeNode: [],
      checkStrictly: true,
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      graphDatasource: {
        nodes: [],
        edges: []
      },
      validatorRules: {
        departName: [{required: true, message: '请输入机构/分类名称!'}],
        orgCode: [{required: true, message: '请输入机构编码!'}],
        orgCategory: [{required: true, message: '请输入机构类型!'}],
        mobile: [{validator: this.validateMobile}]
      },
      url: {
        delete: '/category/pmsCategory/delete',
        edit: '/category/pmsCategory/edit',
        deleteBatch: '/category/pmsCategory/deleteBatch',
        tree: '/category/pmsCategory/antdvTree',
        updateBatchMain: '/category/pmsCategory/editBatch'
      },
      orgCategoryDisabled: false,
      // 层级限制：这里默认层级限制为3
      maxTreeLayer: 3,
      // 是否开启层级限制
      openMaxLayer: true,
      isDragging: false,
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    /**
     * 主要用于打开添加状态的分类模态框
     * @param num  1：新增分类需要自己设置父分类  2：用户会先选择分类，打开模态框后，夫分类就是用户所选择的分类
     * @returns {boolean}
     */
    handleAdd(num) {
      if (num === 1) {
        this.$refs.categoryModal.add()
        this.$refs.categoryModal.title = '新增'
      } else if (num === 2) {
        // 用户先选择好的分类
        let key = this.currSelected.catId
        if (!key) {
          this.$message.warning('请先点击选中上级分类！')
          return false
        }
        this.$refs.categoryModal.add(this.selectedKeys)
        this.$refs.categoryModal.title = '新增'
      } else {
        this.$refs.categoryModal.add(this.rightClickSelectedKey)
        this.$refs.categoryModal.title = '新增'
      }
    },

    onDragend(info) {
      if (this.categoryList.length > 0) {
        this.updateBatch(this.categoryList);
      } else {
        // 拖拽完成
        this.isDragging = false
      }
      this.categoryList = []
    },

    /**
     * 前端更新tree控件: 修改treeData, savingCategoryList
     * @param drop   存放放到的节点
     * @param drag   被拖拽的节点
     * @param dropToGap  是否落在存放节点的旁边或里面
     * @param dropPosition  如果落在节点里面，这里表示落在节点的前边还是后边
     */
    updateTree(drop, drag, dropToGap, dropPosition) {
      let categoryList = []
      let dropCategory = drop.dataRef
      let dragCategory = drag.dataRef
      let originalLevel = dragCategory.catLevel
      let diff = dropCategory.catLevel - originalLevel

      // 是否落在间隙里面
      if (dropToGap) {
        // 修改拖拽节点parentCid
        dragCategory.parentCid = dropCategory.parentCid;
        if (dropPosition === -1) {

          // 放到存放节点的前边
          dragCategory.sort = dropCategory.sort
          dragCategory.catLevel = dropCategory.catLevel

          // 修改被插入节点的排序
          dropCategory.sort = dropCategory.sort + 1
          categoryList.push(dropCategory)

          // 修改被插入节点后边所有节点的排序
          this.allTreeNode.filter(node => node.parentCid === dropCategory.parentCid && node.sort > dragCategory.sort).map(node => {
            node.sort = node.sort + 1
            categoryList.push(node)
          })

        } else if (dropPosition === 1) {
          // 放到后边
          dragCategory.sort = dropCategory.sort + 1
          dragCategory.catLevel = dropCategory.catLevel

          // 修改被插入节点后边所有节点的排序
          this.allTreeNode.filter(node => node.parentCid === dropCategory.parentCid && node.sort > dragCategory.sort).map(node => {
            node.sort = node.sort + 2
            categoryList.push(node)
          })

        }
      } else {
        // 落在drop节点里面
        dragCategory.parentCid = dropCategory.key
        dragCategory.catLevel = dropCategory.catLevel + 1
        let sort = 0;
        // 获取dropCategory节点的所有子节点
        this.allTreeNode.filter(node => node.parentCid === dropCategory.key).map(node => {
          if (node.sort > sort) {
            sort = node.sort
          }
        })
        dragCategory.sort = sort + 1
      }

      // 批量修改等级
      this.forEachCategory(dragCategory, (category) => {
        if (category.key !== dragCategory.key) {
          console.log("forEachCategory")
          console.log(category)
          category.catLevel = category.catLevel + diff
          categoryList.push(category);
        }
      })

      categoryList.push(dragCategory)

      this.categoryList = categoryList
    },

    // 批量更新category数据
    updateBatch(categoryList) {
      putAction(this.url.updateBatchMain, {
        categoryList
      }).then((res) => {
        if (res.success) {
          this.$message.success(res.message);
        } else {
          this.$message.warning(res.message);
        }
      }).finally(() => {
        // 拖拽完毕
        this.isDragging = false
        this.refresh()
      })
    },


    /**
     * 拖拽方法
     * @param info
     */
    onDrop(info) {
      if (this.isDragging) {
        this.$message.warn("上一个拖拽任务未完成");
      }
      // 正在拖拽
      this.isDragging = true
      // 丢到的地方的key
      const dropKey = info.node.eventKey;
      // 被拖动的key
      const dragKey = info.dragNode.eventKey;
      // 丢到的位置
      const dropPos = info.node.pos.split('-');
      let isOutOf = this.isOutOfBounds(info.node, info.dragNode, info.dropToGap);
      if (!isOutOf) {
        this.$message.warn("当前分类默认最大层级是" + this.maxTreeLayer + "级");
        // 拖拽完毕
        this.isDragging = false
        return false
      }
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
      this.updateTree(info.node, info.dragNode, info.dropToGap, dropPosition);
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.key === key) {
            return callback(item, index, arr);
          }
          if (item.children) {
            return loop(item.children, key, callback);
          }
        });
      };
      const data = [...this.treeData];

      // Find dragObject
      let dragObj;
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1);
        dragObj = item;
      });
      if (!info.dropToGap) {
        // console.log("on the content")
        let ar;
        // Drop on the content
        loop(data, dropKey, (item, index, arr) => {
          item.children = item.children || [];
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.push(dragObj);
          ar = arr
        });
        // console.log(dragKey)
      } else if (
        (info.node.children || []).length > 0 && // Has children
        info.node.expanded && // Is expanded
        dropPosition === 1 // On the bottom gap
      ) {
        loop(data, dropKey, item => {
          item.children = item.children || [];
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.unshift(dragObj);
        });
      } else {
        let ar;
        let i;

        loop(data, dropKey, (item, index, arr) => {
          // console.log(arr)
          ar = arr;
          i = index;
        });
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj);
        } else {
          ar.splice(i + 1, 0, dragObj);
        }
      }
      this.treeData = data;
      this.departTree = data;
    },

    /**
     * 判断当前控件是否超出层级限制
     * @param drop 被拖动到的节点
     * @param drag 拖动节点
     * @param dropToGap 是否落到间隙里面
     */
    isOutOfBounds(drop, drag, dropToGap) {
      let dropCategory = drop.dataRef
      let dragCategory = drag.dataRef

      if (this.openMaxLayer) {
        // 先做简单的层级判断
        let dropLayer = dropCategory.level + 1
        if (dropToGap) {
          dropLayer--;
        }
        if (dropLayer > this.maxTreeLevel) {
          return false;
        } else {
          let dragLayer = this.getLayer(dragCategory)
          if (dropLayer + dragLayer > this.maxTreeLayer) {
            return false;
          }
        }
      }

      return true;
    },

    /**
     * 遍历某个节点，获取该节点的最大层级
     */
    getLayer(category) {
      if (category.children == null || category.children.length === 0) {
        return 1;
      }

      const loop = (data, callback, deep) => {
        if (!deep) {
          deep = 1
        }
        if (data.children) {
          callback(data, deep)
          deep++
          data.children.forEach((item) => {
            loop(item, callback, deep);
          })
        } else {
          deep++
          callback(data, deep);
        }
      }

      let layer = 0;
      loop(category, (item, deep) => {
        if (parseInt(deep) > layer) {
          layer = parseInt(deep)
        }
      })

      return layer;
    },

    forEachCategory(data, callback) {
      if (data.children) {
        callback(data)
        data.children.forEach((item, index, arr) => {
          this.forEachCategory(item, callback);
        })
      } else {
        callback(data);
      }
    },

    loadData() {
      this.refresh()
    },

    loadTree() {
      var that = this
      that.treeData = []
      that.departTree = []
      this.$http.get(this.url.tree).then((res) => {
        if (res.success) {
          //分类全选后，再添加分类，选中数量增多
          this.allTreeKeys = []
          this.allTreeNode = []
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.treeData.push(temp)
            that.departTree.push(temp)
            console.log("test")
            that.setThisExpandedKeys(temp)
            that.getAllKeys(temp)
            // console.log(temp.id)
          }
          this.loading = false
        }
      })
    },

    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },

    refresh() {
      this.loading = true
      this.loadTree()
    },

    // 右键操作方法
    rightHandle(node) {
      this.dropTrigger = 'contextmenu'
      this.rightClickSelectedKey = node.node.eventKey
      this.rightClickSelectedOrgCode = node.node.dataRef.orgCode
    },

    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },

    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },

    // 右键下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },

    batchDel: function () {
      console.log("batchDel")
      console.log(this.checkedKeys)
      if (this.checkedKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.checkedKeys.length; a++) {
          ids += this.checkedKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '确定要删除所选中的 ' + this.checkedKeys.length + ' 条数据，以及子节点数据吗?',
          onOk: function () {
            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadTree()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },

    onSearch(value) {
      let that = this
      if (value) {
        searchByKeywords({keyWord: value}).then((res) => {
          if (res.success) {
            that.departTree = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.departTree.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },

    nodeModalOk() {
      this.loadTree()
    },

    nodeModalClose() {

    },

    onCheck(checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
      this.hiding = false
      //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked
      } else {
        this.checkedKeys = checkedKeys
      }
      //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
    },

    onSelect(selectedKeys, e) {
      console.log('selected', selectedKeys, e)
      this.hiding = false
      let record = e.node.dataRef
      console.log('onSelect-record', record)
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedKeys = [record.key]
      this.model.parentId = record.parentId
      this.setValuesToForm(record)
      // this.$refs.departAuth.show(record.id)
    },

    // 触发onSelect事件时,为分类树右侧的form表单赋值
    setValuesToForm(record) {
      if (record.orgCategory == '1') {
        this.orgCategoryDisabled = true
      } else {
        this.orgCategoryDisabled = false
      }
    },

    getCurrSelectedTitle() {
      return !this.currSelected.title ? '' : this.currSelected.title
    },

    onClearSelected() {
      this.hiding = true
      this.checkedKeys = []
      this.currSelected = {}
      this.selectedKeys = []
      this.$refs.departAuth.departId = ''
    },
    handleNodeTypeChange(val) {
      this.currSelected.nodeType = val
    },
    notifyTriggerTypeChange(value) {
      this.currSelected.notifyTriggerType = value
    },
    receiptTriggerTypeChange(value) {
      this.currSelected.receiptTriggerType = value
    },
    submitCurrForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.currSelected.id) {
            this.$message.warning('请点击选择要修改分类!')
            return
          }

          httpAction(this.url.edit, this.currSelected, 'put').then((res) => {
            if (res.success) {
              this.$message.success('保存成功!')
              this.loadTree()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    emptyCurrForm() {
      this.$refs.form.resetFields()
      this.model = {}
    },
    nodeSettingFormSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log('Received values of form: ', this.model)
        }
      })
    },
    openSelect() {
      this.$refs.sysDirectiveModal.show()
    },
    handleDelete() {
      var that = this
      this.$confirm({
        title: '确认删除',
        content: '确定要删除此分类以及子节点数据吗?',
        onOk: function () {
          deleteByDepartId({id: that.rightClickSelectedKey}).then((resp) => {
            if (resp.success) {
              //删除成功后，去除已选中中的数据
              that.checkedKeys.splice(that.checkedKeys.findIndex(key => key === that.rightClickSelectedKey), 1)
              that.$message.success('删除成功!')
              that.loadTree()
              //删除后同步清空右侧基本信息内容
              let orgCode = that.model.orgCode
              if (orgCode && orgCode === that.rightClickSelectedOrgCode) {
                that.onClearSelected()
              }
            } else {
              that.$message.warning('删除失败!')
            }
          })
        }
      })
    },
    selectDirectiveOk(record) {
      console.log('选中指令数据', record)
      this.nodeSettingForm.setFieldsValue({directiveCode: record.directiveCode})
      this.currSelected.sysCode = record.sysCode
    },
    getFlowGraphData(node) {
      this.graphDatasource.nodes.push({
        id: node.id,
        text: node.flowNodeName
      })
      if (node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          let temp = node.children[a]
          this.graphDatasource.edges.push({
            source: node.id,
            target: temp.id
          })
          this.getFlowGraphData(temp)
        }
      }
    },
    //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.iExpandedKeys = []
    },
    checkALL() {
      this.checkStriccheckStrictlytly = false
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      //this.checkedKeys = this.defaultCheckedKeys
      this.checkedKeys = []
    },
    switchCheckStrictly(v) {
      if (v == 1) {
        this.checkStrictly = false
      } else if (v == 2) {
        this.checkStrictly = true
      }
    },
    getAllKeys(node) {
      // console.log('node',node);
      this.allTreeKeys.push(node.key)
      this.allTreeNode.push(node)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllKeys(node.children[a])
        }
      }
    },
    //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
  },
  created() {
    this.currFlowId = this.$route.params.id
    this.currFlowName = this.$route.params.name
    // this.loadTree()
  },


}
</script>
<style scoped>
.ant-card-body .table-operator {
  margin: 15px;
}

.anty-form-btn {
  width: 100%;
  text-align: center;
}

.anty-form-btn button {
  margin: 0 5px;
}

.anty-node-layout .ant-layout-header {
  padding-right: 0
}

.header {
  padding: 0 8px;
}

.header button {
  margin: 0 3px
}

.ant-modal-cust-warp {
  height: 100%
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden
}

#app .desktop {
  height: auto !important;
}

/** Button按钮间距 */
.ant-btn {
  margin-left: 3px
}

.drawer-bootom-button {
  /*position: absolute;*/
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: left;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>